package com.oren.config;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oren.Bean.View;
import com.oren.util.ArrayUtil;
import com.oren.util.ReflectionUtil;
import com.oren.util.StreamUtil;
import com.oren.util.StringUtil;
import com.oren.Bean.Data;
import com.oren.Bean.Param;
import com.oren.Bean.WswHandler;
import com.oren.util.CodeUtil;
import com.oren.util.JsonUtil;

/**  
* @description 请求转发器
* @author  wangshiwei  
* @date   2018年6月22日 下午4:12:17
    
*/
@WebServlet(urlPatterns = "/*", loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet{
	
	
	@Override
	public void init(ServletConfig servletConfig) throws ServletException{
	    //初始化helpher类
	    HelperLoader.init();
	    //获取ServletContext对象 用于注册servlet
	    ServletContext servletContext= servletConfig.getServletContext();
	    //注册处理jsp
	    ServletRegistration jsRegistration=servletContext.getServletRegistration("jsp");
		String s=ConfigHelper.getJspPath();
	    System.out.println("jsp路径为"+s);
	    jsRegistration.addMapping(ConfigHelper.getJspPath()+"*");
	    //注册处理静态资源的默认serlvet
	    ServletRegistration defaultServlet=servletContext.getServletRegistration("default");
	    defaultServlet.addMapping(ConfigHelper.getStaticPath()+"*");
	}
	@Override
	public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
	    //获取请求的方法和路径
	    //String requestMethod=req.getMethod().toLowerCase();
		String requestPath=req.getPathInfo();
	    String UrlMethod="";
	    String urlPath="";

		if(StringUtil.appearNumber(requestPath,"/")==2) {
			String path[] = requestPath.split("/");
			urlPath = path[1];
			UrlMethod = path[2];
		}
	   WswHandler handler= ControllerHelper.getHandler(urlPath, UrlMethod);
	 //  WswHandler handler=ControllerHelper.getHandler(requestMethod, requestPath);

	    if(handler!=null) {
		    //获取controller类以及bean的实例
			Class<?> controllerClass=handler.getControllerClass();
			Object controllerBean=BeanHelper.getBean(controllerClass);
			//创建请求参数对象
			Map<String,Object> paramMap=new HashMap<String,Object>();
			Enumeration<String> paramNames=req.getParameterNames();
			while(paramNames.hasMoreElements()) {
				String paramName=paramNames.nextElement();
				String paramValue=req.getParameter(paramName);
				paramMap.put(paramName, paramValue);
			}
			String body=CodeUtil.decodeURL(StreamUtil.getString(req.getInputStream()));
			if(!StringUtil.isEmpty(body)) {
				String [] params=body.split("&");
				if(!ArrayUtil.isNotEmpty(params)) {
					for (String param : params) {
						String[] array=param.split("=");
						if(!ArrayUtil.isNotEmpty(array)&&array.length==2) {
							String paramName=array[0];
							String paramValue=array[1];
							paramMap.put(paramName, paramValue);
						}
					}
				}
		}
		Object result;
		Method actionMethod=handler.getActionMethod();
		Param param=new Param(paramMap);
		//判断输入参数是否为空
		if(param.isEmpty()){
			result= ReflectionUtil.invokeMethod(controllerBean, actionMethod);
		}else{
			result=ReflectionUtil.invokeMethod(controllerBean, actionMethod,param);
		}

		//处理action方法的返回值
		if(result instanceof View) {
			//返回jsp页面
		    View view =(View)result;
		    String path=view.getPath();
		    if(!StringUtil.isEmpty(path)) {
			if(path.startsWith("/")) {
			    res.sendRedirect(req.getContextPath()+path);
			}else {
			    Map<String,Object> model=view.getModel();
			    for (Map.Entry<String, Object> entry : model.entrySet()) {
				req.setAttribute(entry.getKey(), entry.getValue());
			    }
			    String sss=ConfigHelper.getJspPath()+path;
			    System.out.println("jsp路径地址为:"+sss);
			    req.getRequestDispatcher(sss).forward(req, res);
			}
		    }
		}else if(result instanceof Data) {
		    Data data=(Data)result;
		    Object model=data.getModel();
		    if(model!=null) {
			res.setContentType("application/json");
			res.setCharacterEncoding("UTF-8");
			PrintWriter writer=res.getWriter();
			String json=JsonUtil.pojoToJson(model);
			writer.write(json);
			writer.flush();
			writer.close();
		    }
		}
	    }
	}		
}
